package turn;

import java.io.*;

public class TurnStream {

    public static void main(String[] args) throws IOException {
        File file = new File("day09-code/src/file/a.txt");
        File file1 = new File("day09-code/src/file/b.txt");
        //转换流，将字节流转换成字符流，它本身就是字符流，只能转字节流
        InputStreamReader isr = new InputStreamReader(new FileInputStream(file));
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(file1));

        copy(new FileInputStream(file), new FileOutputStream(file1), file);

    }

    private static void copy(FileInputStream fis, FileOutputStream fos, File file) {
        InputStreamReader isr = null;
        OutputStreamWriter osw = null;
        try {
            if (file.getName().endsWith(".txt") || file.getName().endsWith(".java")) {
                isr = new InputStreamReader(fis);
                osw = new OutputStreamWriter(fos);

                System.out.println("使用字符流");
                char[] car = new char[1024];
                int len;
                while ((len = isr.read(car)) != -1) {
                    osw.write(String.valueOf(car, 0, len));
                    osw.flush();
                }
            } else {
                System.out.println("使用字节流");
                byte[] car = new byte[1024];
                int len;
                while ((len = fis.read(car)) != -1) {
                    fos.write(car, 0, len);
                    fos.flush();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
